package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.bp_detect

import android.annotation.SuppressLint
import android.content.Intent
import android.hardware.Camera
import android.hardware.Camera.PreviewCallback
import android.os.CountDownTimer
import android.os.Handler
import android.os.HandlerThread
import android.os.PowerManager
import android.os.PowerManager.WakeLock
import android.view.SurfaceHolder
import android.view.View
import androidx.lifecycle.Observer
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.AdError
import com.anythink.interstitial.api.ATInterstitial
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdManager
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.TopOnInterAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.listener.manual_load.TopOnInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseActivity
import com.bp.hearthealth.pulse.lnapps.base.bp_liveDataBus.BpLiveDataBus
import com.bp.hearthealth.pulse.lnapps.databinding.ActivityHeartrateBgBinding
import com.bp.hearthealth.pulse.lnapps.bp_extension.BpGlobalUtil
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_extension.UIHelperBp
import com.bp.hearthealth.pulse.lnapps.bp_itfc.OnBpCountdownListener
import com.bp.hearthealth.pulse.lnapps.bp_utils.TimerCallback
import com.bp.hearthealth.pulse.lnapps.bp_utils.TimerUtil
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.BpHeartRateViewModel
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.bp_guide.BpHeartRateGuideActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.bp_report.BpHeartRateReportActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_main.BpMainActivity
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.VibrationUtils
import com.bp.hearthealth.pulse.lnapps.bp_view.BPCircleViewOutlineProvider
import com.hjq.toast.Toaster
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 检测心率
 */
class BpHeartRateActivity : BpBaseActivity<ActivityHeartrateBgBinding>(), TimerCallback,
    OnBpCountdownListener {

    private var isResetView: Boolean = true
    private var countDownTimer: CountDownTimer? = null
    private lateinit var timerUtil: TimerUtil
    private var endAverage: Int = 0

    //预览设置信息
    private var previewHolder: SurfaceHolder? = null
    private var camera: Camera? = null
    private var wakeLock: WakeLock? = null
    private val viewModel: BpHeartRateViewModel by viewModel()
    private lateinit var cameraHandler: Handler

    override fun initListener() {
        super.initListener()
        //心率检测页展示  hr_measure_show
        AppsFlyerUtils.trackEvent("hr_measure_show")
        binding.apply {
            countdownCircleView.setOnCountdownListener(this@BpHeartRateActivity)
            constraintGuide.setOnClickListener {
                startActivity(Intent(activity, BpHeartRateGuideActivity::class.java))
            }
            ivBack.setOnClickListener {
                //展示插页广告
//                loadAdMobInsertAd()
                loadTopOnInsertAd()
            }
        }
    }


    override fun initData() {
        super.initData()
        binding.lifecycleOwner = this
        binding.viewModel = viewModel
        initSurfaceView()
        if (!AdsSwitch.getBoolean(AdsSwitch.adInterCacheControl)) {
            TopOnInterAdManager.initManualLoadInterstitialAd(this)
            TopOnInterAdManager.manualLoadAd()
        }
        registerObserver()
//        if (BuildConfig.DEBUG) {
//            viewModel.insertHeartRateBean(Constants.USER_ID, 88)
//        }
        timerUtil = TimerUtil()
        timerUtil.startTimer(this@BpHeartRateActivity)
    }

    private fun registerObserver() {
        viewModel.insertHeartRateResult.observe(this, Observer { result ->
            val response = result.getOrNull()
            if (response == null) {
                Toaster.show(result.exceptionOrNull())
                result.exceptionOrNull()?.printStackTrace()
                return@Observer
            }
            LogUtil.i("心率数据保存成功")
            BpLiveDataBus.with<Boolean>(Constants.REFRESH_HEART_RATE).postData(true)
            //展示插页广告
//            loadAdMobInsertAd(response)
            loadTopOnInsertAd(response)
        })
        //重置
        viewModel.resetView.observe(this) {
            if (isResetView) {
                isResetView = false
                resetView()
            }
        }
        //开始检测
        viewModel.startHeart.observe(this) { start ->
            if (start) {
                isResetView = true
                binding.heartRate.playAnimation()
                binding.heartRate.visibility = View.VISIBLE
                binding.ivLine.visibility = View.INVISIBLE
                timerUtil.stopTimer()
                binding.countdownCircleView.startProgressAnimation(Constants.HEART_RATE_TIME)
            }
        }
    }

    private fun initSurfaceView() {
        binding.apply {
            previewHolder = preview.holder
            previewHolder!!.addCallback(object : SurfaceHolder.Callback {
                //创建时调用
                override fun surfaceCreated(holder: SurfaceHolder) {
//                    val handlerThread = HandlerThread("CameraThread")
//                    handlerThread.start()
//                    cameraHandler = Handler(handlerThread.looper)
//
//                    cameraHandler.post {
//                        camera = Camera.open()
//
//                        try {
//                            camera!!.setPreviewDisplay(previewHolder)
//                            camera!!.setPreviewCallback(previewCallback)
//                            camera!!.startPreview()
//
//                        } catch (e: Exception) {
//                            e.printStackTrace()
//                        }
//                    }
                    try {
                        camera!!.setPreviewDisplay(previewHolder)
                        camera!!.setPreviewCallback(previewCallback)
                    } catch (t: Throwable) {
                        LogUtil.e("Exception in setPreviewDisplay()", t)
                    }
                }

                override fun surfaceChanged(
                    holder: SurfaceHolder,
                    format: Int,
                    width: Int,
                    height: Int,
                ) {
                    val parameters: Camera.Parameters = camera!!.parameters
                    parameters.flashMode = Camera.Parameters.FLASH_MODE_TORCH
                    val size = BpGlobalUtil.getSmallestPreviewSize(width, height, parameters)
                    if (size != null) {
                        parameters.setPreviewSize(size.width, size.height)
                    }
                    camera!!.parameters = parameters
                    camera!!.startPreview()
                }

                //销毁的时候调用
                override fun surfaceDestroyed(holder: SurfaceHolder) {}
            })
            previewHolder!!.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
            val pm = getSystemService(POWER_SERVICE) as PowerManager
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this@BpHeartRateActivity.javaClass.getName())//持有唤醒锁

            preview.outlineProvider = BPCircleViewOutlineProvider()
            preview.clipToOutline = true
        }
    }


    private val previewCallback = PreviewCallback { data: ByteArray?, cam: Camera ->
        if (data == null) {
            throw NullPointerException()
        }
        viewModel.previewCallback(data, cam)
    }

    private fun resetView() {
        timerUtil.resetTimer()
        countDownTimer?.cancel()
        timerUtil.startTimer(this)
        binding.apply {
            tvHeartRate.text = "00"
            tvStatus.text = getString(R.string._heartrate_title_str1)
            tvStatusDes.text = getString(R.string._heartrate_des_str1)
            countdownCircleView.pauseCountdown()
            heartRate.visibility = View.INVISIBLE
            ivLine.visibility = View.VISIBLE
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        TopOnInterAdManager.setManualLoadListener(null)
        timerUtil.stopTimer()
    }

    @SuppressLint("MissingPermission")
    private fun initCamera() {
        camera = Camera.open()
        viewModel.startTime = System.currentTimeMillis()
    }

    override fun onResume() {
        super.onResume()
        isResetView = true
        wakeLock?.setReferenceCounted(false)
        wakeLock?.acquire()
        initCamera()
    }

    override fun onPause() {
        super.onPause()
        releaseCamera()
    }

    private fun releaseCamera() {
        resetView()
        wakeLock?.release()
        camera?.let {
            it.setPreviewCallback(null)
            it.stopPreview()
            it.release()
        }
        camera = null
    }


    override fun onTimerGreaterThanFifteen() {
        binding.tvStatus.text = getString(R.string._heartrate_title_str2)
        binding.tvStatusDes.text = getString(R.string._heartrate_des_str2)
        VibrationUtils.stopVibration()
        LogUtil.i("震动停止")
    }

    @SuppressLint("SetTextI18n")
    override fun onCountdownFinished(number: Int) {
        releaseCamera()
        VibrationUtils.stopVibration()
        binding.tvStatus.text = "${UIHelperBp.getString(R.string._heartrate_title_str3)}(${100}%)"
        LogUtil.i("onCountdownFinished $endAverage")
        endAverage = viewModel.averageSize / viewModel.averageData.size
        viewModel.beatsAvgUi.set(endAverage.toString())
        viewModel.insertHeartRateBean(Constants.USER_ID, endAverage) //结束
    }

    @SuppressLint("SetTextI18n")
    override fun onCountdownProgress(number: Int) {
        if (number != 0 && !VibrationUtils.isVibrating()) {
            VibrationUtils.vibratePattern(longArrayOf(0, 100, 1000, 100, 1000))
        }
        val progress = ((number / 1000) / 15.0) * 100
        val formattedResult = String.format("%.0f", progress)
        if (_binding != null) {
            binding.tvStatus.text =
                "${getString(R.string._heartrate_title_str3)}(${formattedResult}%)"
        }
        LogUtil.i("onCountdownProgress: $formattedResult")
    }

    /**
     * ○ 点击取消入口，展示插页广告
     *     ■ 插页广告资源加载到，立即展示，广告关闭后自动跳转至上一级页面
     *     ■ 插页广告资源未加载到，自动跳转至上一级页面
     *  空:销毁
     *  非空:跳转新activity
     *
     */
    private fun loadAdMobInsertAd(vararg id: Long) {
        VibrationUtils.stopVibration()
        binding.countdownCircleView.setOnCountdownListener(null)
        binding.countdownCircleView.cancelMessage(true)
        AdMobInterstitialAdManager.setInterstitialAdListener(object : AdMobInterstitialAdListener {
            override fun onAdDismissedFullScreenContent() {
                startJumpActivity(id)
            }

            override fun onAdFailedToShowFullScreenContent() {
                startJumpActivity(id)
            }

            override fun onNotReady() {
                startJumpActivity(id)
            }

            override fun onAdShowedFullScreenContent() {
                if (id.isEmpty()) {
                    //点击取消按钮后_插页广告 ad_inter_hr_measure_cancel_show
                    AppsFlyerUtils.trackEvent("ad_inter_hr_measure_cancel_show")
                    ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID, "f66471efee16e8")
                    LogUtil.iTopOn("TopOn 配置的场景ID为: 【Heart Rate测试点击取消按钮后_插页广告】")
                } else {
                    //测试进度完成后_插页广告 ad_inter_hr_measure_finish_show
                    AppsFlyerUtils.trackEvent("ad_inter_hr_measure_finish_show")
                    ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID, "f66471ef0669d6")
                    LogUtil.iTopOn("TopOn 配置的场景ID为: 【Heart Rate测试进度完成后_插页广告】")
                }
            }
        })
        AdMobInterstitialAdManager.showInterstitialAd(this)
    }

    private fun loadTopOnInsertAd(vararg id: Long) {
        VibrationUtils.stopVibration()
        binding.countdownCircleView.setOnCountdownListener(null)
        binding.countdownCircleView.cancelMessage(true)
        TopOnInterAdManager.setManualLoadListener(object : TopOnInterstitialAdListener {
            override fun onInterstitialAdShow(entity: ATAdInfo) {
                if (id.isEmpty()) {
                    //点击取消按钮后_插页广告 ad_inter_hr_measure_cancel_show
                    AppsFlyerUtils.trackEvent("ad_inter_hr_measure_cancel_show")
                    ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID, "f66471efee16e8")
                    LogUtil.iTopOn("TopOn 配置的场景ID为: 【Heart Rate测试点击取消按钮后_插页广告】")
                } else {
                    //测试进度完成后_插页广告 ad_inter_hr_measure_finish_show
                    AppsFlyerUtils.trackEvent("ad_inter_hr_measure_finish_show")
                    ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID, "f66471ef0669d6")
                    LogUtil.iTopOn("TopOn 配置的场景ID为: 【Heart Rate测试进度完成后_插页广告】")
                }
            }

            override fun onFireBaseAdIsClosed() {
                startJumpActivity(id)
            }

//            override fun onInterstitialAdLoaded() {
//                LogUtil.iTopOn("插页广告 onInterstitialAdLoaded 回调")
//                if (TopOnInterAdManager.isAdReady()) {
//                    TopOnInterAdManager.mInterstitialAd!!.show(this@BpHeartRateActivity)
//                } else {
//                    startJumpActivity(id)
//                }
//            }

            override fun onInterstitialAdClose(entity: ATAdInfo) {
                startJumpActivity(id)
            }

            override fun onInterstitialAdLoadFail(adError: AdError) {
                startJumpActivity(id)
            }

            override fun onInterstitialAdVideoError(adError: AdError) {
                startJumpActivity(id)
            }

            override fun onNotReady() {
                startJumpActivity(id)
            }
        })
        TopOnInterAdManager.showInterstitialAd(this)
    }


    private fun startJumpActivity(id: LongArray) {
        TopOnInterAdManager.setManualLoadListener(null)
        if (!this.isDestroyed) {
            if (id.isEmpty()) {
                startActivity(Intent(this, BpMainActivity::class.java))
            } else {
                val intent = Intent(this, BpHeartRateReportActivity::class.java)
                intent.putExtra("id", id[0])
                intent.putExtra("type", Constants.HEART_RATE)
                startActivity(intent)
            }
        }
        finish()
    }

    @Deprecated("Deprecated in Java", ReplaceWith("finish()"))
    override fun onBackPressed() {
//        loadAdMobInsertAd()
        loadTopOnInsertAd()
    }
}